<?php

namespace Home\Controller;

class QcodeController extends BaseController {

    public function index() {
        $id = I('id', 0, 'intval');

        if ($id == 0) {
            $this->error('错误的ID');
        }

        $car_info = M('Car')
                ->table('ot_car c')
                ->field('u.*,c.car_id,c.car_number,c.msg,c.car_str')
                ->join('ot_users u on c.user_id = u.user_id')
                ->where(['c.car_id' => $id])
                ->find();


        //CODE  801代表自己的车  800表示挪车牌还没绑定车辆 
        if ($car_info) {
            $code = 0;
            if ($car_info['user_id'] == $this->user_id) {
                $code = 801;
            }
            $age = birthday($car_info['brithday']);
            if ($age < 0) {
                $age = 0;
            }
            $car_info['age'] = $age;
            $this->success('获取成功', $car_info, $code);
        } else {
            $code = 800;
            $this->success('空的挪车牌', [], $code);
        }
    }

    public function add() {
        $id = I('id', 0, 'intval');

        if ($id == 0) {
            $this->error('错误的ID');
        }

        $car_info = M('Car')->where(['car_id' => $id])->find();

        if ($car_info) {
            $this->error('此挪车牌已被别人抢先一步占用了哦');
        }

        $car_str = I('car_str');
        $car_number = I('car_number');
        $phone = I('phone');

        if (empty($car_str)) {
            $this->error('请选择车牌前缀');
        }

        if (empty($car_number)) {
            $this->error('请输入车牌号');
        }


        $car_number = strtoupper($car_number);

        $data['car_id'] = $id;
        $data['user_id'] = $this->user_id;
        $data['car_str'] = $car_str;
        $data['car_number'] = $car_number;
        $data['msg'] = '临时停靠,请多关照';

        try {
            D()->startTrans();
            $res = M('Car')->add($data);

            if (!empty($phone)) {
                M('Users')->where(['user_id' => $this->user_id])->save(['phone' => $phone]);
            }

            D()->commit();
            $this->success('绑定成功!');
        } catch (Exception $ex) {
            $this->error('网络错误,请稍后重试');
        }
    }

}
